<%--
  Created by IntelliJ IDEA.
  User: Yi
  Date: 2025/9/17
  Time: 11:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="header.jsp"/>

<style>
    :root {
        --primary-color: #4a6fc0;
        --primary-hover: #3b5aa6;
        --secondary-color: #6c757d;
        --success-color: #198754;
        --danger-color: #dc3545;
        --light-bg: #f8f9fa;
        --border-color: #dee2e6;
    }

    body {
        background-color: #f5f7fb;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        color: #333;
    }

    .form-container {
        background: white;
        border-radius: 15px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        margin-bottom: 2rem;
        max-width: 1000px;
        margin: 0 auto;
    }

    .form-header {
        background: white;
        color: #333;
        padding: 1.8rem 2rem;
        text-align: center;
        position: relative;
        border-bottom: 1px solid var(--border-color);
    }

    .form-header h1 {
        font-weight: 600;
        margin-bottom: 0.5rem;
        color: var(--primary-color);
    }

    .form-header p {
        opacity: 0.8;
        margin-bottom: 0;
        color: var(--secondary-color);
    }

    .form-body {
        padding: 2.5rem 2rem;
    }

    .section-title {
        font-size: 1.2rem;
        font-weight: 600;
        color: var(--primary-color);
        margin-bottom: 1.2rem;
        padding-bottom: 0.5rem;
        border-bottom: 2px solid var(--light-bg);
        display: flex;
        align-items: center;
    }

    .section-title i {
        margin-right: 10px;
        font-size: 1.4rem;
    }

    .course-item {
        cursor: move;
        transition: all 0.3s ease;
        border-left: 4px solid #3b7ddd;
        background: white;
        border-radius: 8px;
        margin-bottom: 15px;
        padding: 1rem;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    }

    .course-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }

    .drag-handle {
        cursor: move;
        color: var(--secondary-color);
    }

    .sortable-placeholder {
        border: 2px dashed #ccc;
        background-color: #f8f9fa;
        border-radius: 8px;
        margin-bottom: 15px;
        height: 80px;
    }

    .btn {
        padding: 0.7rem 1.5rem;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s;
    }

    .btn-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
        border-color: var(--primary-hover);
        transform: translateY(-2px);
    }

    .btn-secondary {
        background-color: var(--secondary-color);
        border-color: var(--secondary-color);
    }

    .btn-secondary:hover {
        background-color: #5a6268;
        border-color: #5a6268;
    }

    .save-message {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1050;
    }

    .search-info {
        background-color: #e7f1ff;
        border-left: 4px solid var(--primary-color);
        padding: 1rem;
        border-radius: 0.375rem;
        margin-bottom: 1.5rem;
    }

    .search-info h5 {
        margin-bottom: 0.5rem;
        color: var(--primary-color);
    }

    .search-info p {
        margin-bottom: 0;
    }

    @media (max-width: 768px) {
        .form-body {
            padding: 1.5rem 1rem;
        }

        .form-header {
            padding: 1.2rem 1rem;
        }
    }

    /* 调试信息 */
    .debug-info {
        background-color: #fff3cd;
        border: 1px solid #ffeaa7;
        padding: 10px;
        margin: 10px 0;
        border-radius: 5px;
    }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">课程排序</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <button type="button" class="btn btn-secondary btn-sm" onclick="goBack()">
            <i class="bi bi-arrow-left-circle"></i> 返回课程管理
        </button>
    </div>
</div>

<div class="form-container">
    <div class="form-body">

        <p class="text-muted mb-4">拖拽课程卡片来调整显示顺序</p>

        <div class="row justify-content-center">
            <div class="col-md-12">
                <c:choose>
                    <c:when test="${empty courses}">
                        <div class="alert alert-warning text-center">
                            <i class="bi bi-info-circle"></i> 没有找到相关课程
                        </div>
                    </c:when>
                    <c:otherwise>
                        <ul id="sortable" class="list-unstyled">
                            <c:forEach items="${courses}" var="course" varStatus="status">
                                <li class="course-item" data-id="${course.id}">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h5 class="mb-1">${course.name}</h5>
                                            <p class="mb-2 text-muted">${course.description}</p>
                                        </div>
                                        <div class="drag-handle">
                                            <i class="bi bi-grip-vertical" style="font-size: 1.5rem;"></i>
                                        </div>
                                    </div>
                                </li>
                            </c:forEach>
                        </ul>
                    </c:otherwise>
                </c:choose>
            </div>
        </div>

        <div class="d-flex justify-content-end gap-2 mt-4">
            <button type="button" class="btn btn-secondary" onclick="goBack()">
                <i class="bi bi-x-circle"></i> 取消
            </button>
            <c:if test="${not empty courses}">
                <button id="saveButton" class="btn btn-primary">
                    <i class="bi bi-save"></i> 保存顺序
                </button>
            </c:if>
        </div>

    </div>
</div>

<!-- 保存状态提示 -->
<div id="saveMessage" class="save-message"></div>

<!-- jQuery UI -->
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<script>
    $(function () {
        // 启用拖拽功能（仅当有课程时）
        if ($('#sortable').length > 0) {
            $('#sortable').sortable({
                placeholder: "sortable-placeholder",
                cursor: "move",
                opacity: 0.8,
                tolerance: "pointer"
            });

            // 禁用文本选择以改善拖拽体验
            $('#sortable').disableSelection();
        }

        // 保存按钮点击事件
        $('#saveButton').click(function () {
            saveCourseOrder();
        });

        // 保存课程顺序函数
        function saveCourseOrder() {
            // 获取当前排序后的课程ID顺序
            const orderedCourses = [];
            $('#sortable li').each(function () {
                orderedCourses.push($(this).data('id'));
            });

            console.log("排序后的课程ID:", orderedCourses); // 添加调试日志

            // 显示保存中状态
            showSaveMessage('保存中...', 'info');

            // 发送到后端API
            $.ajax({
                url: '${pageContext.request.contextPath}/coursemanage/savesort',
                method: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                data: {
                    courseOrder: JSON.stringify(orderedCourses)
                },
                success: function (response) {
                    console.log("保存成功响应:", response); // 添加调试日志
                    if (response.success) {
                        showSaveMessage('保存成功！正在跳转...', 'success');
                        // 使用返回的URL进行跳转，如果没有则使用默认URL
                        const returnUrl = response.returnUrl || '${pageContext.request.contextPath}/coursemanage/?success=' +
                            encodeURIComponent('课程排序保存成功');
                        // 2秒后跳转到指定页面
                        setTimeout(() => {
                            window.location.href = returnUrl;
                        }, 2000);
                    } else {
                        showSaveMessage('保存失败: ' + response.message, 'danger');
                    }
                },
                error: function (xhr, status, error) {
                    console.error('保存失败:', error); // 添加错误日志
                    console.log("错误详情:", xhr.responseText); // 添加详细错误信息
                    showSaveMessage('保存失败，请重试', 'danger');
                }
            });
        }

        // 显示保存状态消息
        function showSaveMessage(message, type) {
            const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
            $('#saveMessage').html(alertHtml);

            // 3秒后自动隐藏成功消息（除了保存成功的消息）
            if (type !== 'success') {
                setTimeout(() => {
                    $('#saveMessage .alert').fadeOut();
                }, 3000);
            }
        }

        // 返回上一页函数 - 跳转到查询结果页面
        window.goBack = function () {
            // 从session中获取返回页面的参数
            const subjectSearchText = '${sessionScope.sortReturnSubjectSearchText}';
            const courseSearchText = '${sessionScope.sortReturnCourseSearchText}';
            const pageIndex = '${sessionScope.sortReturnPageIndex}';

            // 构建返回URL
            let returnUrl = '${pageContext.request.contextPath}/coursemanage/';

            if (subjectSearchText || courseSearchText) {
                const params = [];
                if (subjectSearchText) {
                    params.push('subjectSearchText=' + encodeURIComponent(subjectSearchText));
                }
                if (courseSearchText) {
                    params.push('courseSearchText=' + encodeURIComponent(courseSearchText));
                }
                if (pageIndex && pageIndex !== '1') {
                    params.push('pageIndex=' + encodeURIComponent(pageIndex));
                }

                if (params.length > 0) {
                    returnUrl += '?' + params.join('&');
                }
            }

            window.location.href = returnUrl;
        };
    });

</script>


<jsp:include page="footer.jsp"/>
